/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.menu;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.rpc.BeanService;
import com.je.rbac.service.menu.MenuService;
import com.je.rbac.service.menu.TopMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping(value = "/je/rbac/topMenu/relation")
public class TopMenuRelationController extends AbstractPlatformController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private TopMenuService topMenuService;
    @Autowired
    private BeanService beanService;

    @Override
    @RequestMapping(value = "/doUpdateList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doUpdateList(BaseMethodArgument param, HttpServletRequest request) {
        String funcType = param.getParameter("funcType");
        String updatesels = param.getParameter("updatesels");

        List<DynaBean> lists = beanService.buildUpdateList(param.getStrData(), param.getTableCode());

        List<String> menuIdList = new ArrayList<>();
        for (DynaBean eachMenuRelation : lists) {
            menuIdList.add(eachMenuRelation.getStr("RELATION_MENUMODULE_ID"));
        }

        //修改菜单关联顶部菜单字段
        for (DynaBean headMenu : lists) {
            String menuId = headMenu.getStr("RELATION_MENUMODULE_ID");
            String topMenuId = headMenu.getStr("JE_RBAC_HEADMENU_ID");
            if (!Strings.isNullOrEmpty(menuId) && !Strings.isNullOrEmpty(topMenuId)) {
                DynaBean topMenuBean = topMenuService.selectTopMenuById(topMenuId);
                //添加
                DynaBean menu = metaService.selectOneByPk("JE_CORE_MENU", menuId);
                if (menu.getStr("MENU_LINK_TOPMENU_ID") != null && menu.getStr("MENU_LINK_TOPMENU_ID").indexOf(topMenuId) >= 0) {
                    continue;
                }
                String updateId = topMenuId;
                String updateName = topMenuBean.getStr("HEADMENU_NAME");
                if (!Strings.isNullOrEmpty(menu.getStr("MENU_LINK_TOPMENU_ID"))) {
                    updateId = menu.getStr("MENU_LINK_TOPMENU_ID") + "," + topMenuId;
                    updateName = menu.getStr("MENU_LINK_TOPMENU_NAME") + "," + topMenuBean.getStr("HEADMENU_NAME");
                }
                menuService.updateTopMenuRelationBean(menuId, updateId, updateName);
            }
        }

        if (Strings.isNullOrEmpty(updatesels)) {
            updatesels = "1";
        }
        if (!Strings.isNullOrEmpty(funcType) && !funcType.equals("view") || updatesels.equals("0")) {
            int i = manager.doUpdateList(param, request);
            return BaseRespResult.successResult(String.format("%s 条记录被更新", i));
        } else {
            List<DynaBean> list = manager.doUpdateListAndReturn(param, request);
            List<Object> returnList = new ArrayList<>();
            for (DynaBean dynaBean : list) {
                returnList.add(dynaBean.getValues());
            }
            Long count = Long.valueOf(list.size());
            return new BaseRespResult(returnList, String.format("%s 条记录被更新", count), "操作成功");
        }
    }

    @Override
    @RequestMapping(value = "/doRemove", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doRemove(BaseMethodArgument param, HttpServletRequest request) {
        String topMenuRelationIds = getStringParameter(request, "ids");
        for (String relationId : topMenuRelationIds.split(",")) {
            //顶部菜单子功能bean
            DynaBean topMenuRelationBean = topMenuService.selectTopMenuRelationById(relationId);
            String menuId = topMenuRelationBean.getStr("RELATION_MENUMODULE_ID");
            DynaBean menu = metaService.selectOneByPk("JE_CORE_MENU", menuId);
            String menuTopMenuId = menu.getStr("MENU_LINK_TOPMENU_ID");
            String menuTopMenuName = menu.getStr("MENU_LINK_TOPMENU_NAME");
            String topMenuId = topMenuRelationBean.getStr("JE_RBAC_HEADMENU_ID");
            int deleteIndex = 0;
            for (String delId : menuTopMenuId.split(",")) {
                if (delId.equals(topMenuId)) {
                    break;
                }
                deleteIndex++;
            }
            List<String> updatedIds = new ArrayList<>();
            List<String> updatedNames = new ArrayList<>();
            List<String> menuTopMenuIdArray = Arrays.asList(menuTopMenuId.split(","));
            List<String> menuTopMenuNameArray = Arrays.asList(menuTopMenuName.split(","));
            for (int i = 0; i < menuTopMenuIdArray.size(); i++) {
                if (i != deleteIndex) {
                    updatedIds.add(menuTopMenuIdArray.get(i));
                    updatedNames.add(menuTopMenuNameArray.get(i));
                }
            }
            //清除菜单 关联顶部菜单id，name
            menuService.updateTopMenuRelationBean(menuId, String.join(",", updatedIds), String.join(",", updatedNames));
        }
        return BaseRespResult.successResult(String.format("%s 条记录被删除", manager.doRemove(param, request)));
    }

}
